<?php
namespace addons\yexam\service;


use app\admin\model\yexam\Answer;
use app\admin\model\yexam\Fav;
use app\admin\model\yexam\Note;
use app\admin\model\yexam\QuestionType;
use app\api\controller\yexam\QuestionLog;
use think\Exception;

class Question
{

    public $model;

    public function __construct()
    {
        $this->model = new \app\admin\model\yexam\Unit();
    }

    /**
     * 获取章节练习答题卡
     */
    public function getTestCard($unit_id,$user_id){
        $questionModel = new \app\admin\model\yexam\Question();
        $data = $questionModel
            ->alias("question")
            ->field("question.*,ifnull(log.state,3) as state")
            ->join("yexam_question_log log","question.id=log.question_id and log.type=2 and log.user_id=".$user_id." and log.type_id=".$unit_id,"left")
            ->where(['question.unit_id'=>$unit_id])->order("question.type asc,question.id asc")->select();
        $return = [];
        foreach($data as $v){
            $_return['id'] = $v['id'];
            $_return['state'] = $v['state'] ==3?3:($v['state']==0?1:2);        //1是错2是对3是未答过此题
            $return[] = $_return;
        }
        return $return;
    }


    /**
     * 收藏题目
     * @param $id
     * @param $user_id
     * @return int|void
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException]
     */
    public function favQuestion($id,$user_id){
        $questionModel = new \app\admin\model\yexam\Question();
        if (!$questionInfo = $questionModel->where(['id'=>$id])->find()) {
            return;
        }

        $favModel = new Fav();
        if($favInfo = $favModel->where(['user_id'=>$user_id,'question_id'=>$questionInfo['id']])->find()){
            $favInfo->delete();
            return 1;
        }else{
            $favModel = new Fav();
            $favModel->save([
                'user_id' => $user_id,
                'subject_id' => $questionInfo['subject_id'],
                'library_id' => $questionInfo['library_id'],
                'unit_id' => $questionInfo['unit_id'],
                'question_id' => $questionInfo['id'],
                'createtime' => time()
            ]);

            return 2;
        }
    }


    /**
     * 获取题目详情
     * @throws Exception
     */
    public function getQuestion($question_id,$user_id,$logType,$typeId){
        $questionModel = new \app\admin\model\yexam\Question();
        $field = "id,question_name,type,right_answer,area";
        $field = '*';
        $question = $questionModel->field($field)->where(['id'=>$question_id])->find();
        if(empty($question)){
            return [];
        }else{ //================= 试题存在
            $type = new QuestionType();
            $option = explode('<hr />',$question['questionselect']);
            $question['request_text'] = $type->where('questcode',$question['questiontype'])->value('questype');
            //================================= 旧代买 =----------------= 获取答案 start
            /*{
                if($question['type'] == 3){ //=========== 判断题
                    $question['answers'] = array(
                        '0' => array(
                            'answer' => "对",
                            'answer_code' => "1",
                            'id' => 1,
                            'question_id' => $question['id']
                        ),
                        '1' => array(
                            'answer' => "错",
                            'answer_code' => "0",
                            'id' => 2,
                            'question_id' => $question['id']
                        ),
                    );
                }else{ //== 非判断题正常显示
                    $answerModel = new Answer();
                    $question['answers'] = $answerModel->where(['question_id'=>$question['id']])->select();
                }
            }*/

            //============================== end ======================================
            $arrs = [];

            foreach ($option as $key => $value)
            {
                $code = $key+1;
                array_push($arrs,array(
                    'answer' => $value, //=== 选项名称
                    'answer_code' => $this->intToChr($key),
                    'id' => $code,
                    'question_id' => $question['id'],
//                    'right_flg' => false
                ));
            }

            $question['answers'] = $arrs;
            //==================  检测该试题是否已经作答
            $log = new \app\admin\model\yexam\QuestionLog();
            $where['user_id'] = $user_id;
            $where['type'] = $logType;
            $where['type_id'] = $typeId;
            $where['question_id'] = $question_id;
            $questionType = new QuestionType();
            $qtype = $questionType->where('questcode',$question['questiontype'])->field('question_category')->find();
            $question['type'] = $qtype->getData('question_category');
            $result = $log->where($where)->find();
            $userAnswer = [];
            $userSelect = '';
            $rightAnswer = $question['right_answer'];// 该题目正确的答案
            if ($result) {
                $userSelect = $result->user_answer;//用户选择的答案
                //====== 遍历该题的选项并和用户选择的答案进行比对
                foreach ($question['answers'] as $value)
                {
                    /**
                     * 流程处理
                     * 1.如果该选项用户没有选择显示为FALSE
                     * 2.用户选择的并和答案对比
                    */
                    //====== 用户选择的和当前选项对比
                    if (is_numeric(strpos($userSelect,$value['answer_code'])))
                    {
                        //======= 用户选择正确的选项
                        if ($userSelect == $rightAnswer)
                        {
                            $tmp = [
                                'active' => true,
                                'answer_code' => $value['answer_code'],
                                'error_flg'  => false
                            ];
                        }
                        //======== 用户选择的选项错误
                        else{
                            $tmp = [
                                'active' => true,
                                'answer_code' => $value['answer_code'],
                                'error_flg'  => true
                            ];
                        }
                    }
                    //========== 用户未选择该答案
                    else{
                        $tmp = [
                            'active' => false,
                            'answer_code' => $value['answer_code'],
                            'error_flg'  => false
                        ];
                    }
                    $userAnswer[] = $tmp;
                }
            }
            $question['user_answer'] = $userAnswer;
            $question['uAnswer'] = $userSelect;
            $question['is_answer_ok'] = $userSelect == $rightAnswer ? 1 : 0;
            //====== end
            $favModel = new Fav();
            if($favModel->where(['question_id'=>$question['id'],'user_id'=>$user_id])->count()){
                $question['is_fav'] = 1;
            }else{
                $question['is_fav'] = 0;
            }
            $note = new Note();//
            $noteResult = $note->where('question_id',$question['id'])->where('user_id',$user_id)->find();
            if (!is_null($noteResult))
                $question['note'] = $noteResult->content;
            else
                $question['note'] = '';
        }
        return $question;
    }

    /**
     * ================= 答案选项编号(26个英文字母) ==========
     * @param $index int 字母顺序
     * @param int $start Ascall字母排序
     * @return string 英文字母
     */

    public function intToChr(int $index=0, int $start=65) : string
    {
        return chr($index % 26+$start);
    }
}